import { getProfile, login } from '@/api/user'
import { resetRouter } from '@/router/index'
import { getToken, removeToken, setToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeToken(state) {
    // 删除Vuex的token
    state.token = null
    removeToken()
  }
}
const actions = {
  async login(context, payload) {
    // console.log('login', context, payload)
    const token = await login(payload)
    context.commit('setToken', token)
  },
  logout(context) {
    // 做退出的操作
    // 清空 token, 个人信息
    context.commit('setToken', '')
    context.commit('setUserInfo', {})
    resetRouter()
  },
  async getProfile(context) {
    const result = await getProfile()
    context.commit('setUserInfo', result)
    return result
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
